package org.jobtask.ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.Comparator;

import javax.swing.Box;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

import org.jobtask.config.ResourceMessages;
import org.jobtask.config.SystemIdentification;
import org.jobtask.io.LogIO;
import org.jobtask.schedule.KeyValue;

public class LogViewPort extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3185727944630193015L;
	private File[] currentLogFile=null;
	private LogIO logio=null; 
	private JTextField sequenceField=null;
	private JComboBox taskSelect=null;
	private JComboBox dateSelect=null;
	private JTextArea text=null;
	private Box panel2=Box.createVerticalBox();
	private ItemLabel refreshBut=null;
	private ItemLabel clearBut=null;
	private ItemLabel exitBut=null;
	private ViewPortListener vpListener=null;
	public static boolean isOpen;
	
	public LogViewPort(Object[] kvs){
		this.setIconImage(new ImageIcon(this.getClass().getResource("images/logs.png")).getImage());
		this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		this.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				super.windowClosing(e);
				isOpen=false;
			}
		});
		
		this.initView();
		this.fillTaskNameSelect(kvs);
		this.fillDateTimeSelect();
		this.setMinimumSize(new Dimension(600, 300));
		this.setSize(789,446);
		setLocationRelativeTo(null);
		this.setVisible(true);
		isOpen=true;
	}
	
    private void fillDateTimeSelect(){
    	this.currentLogFile=this.logio.getLogFileList("logs",((KeyValue)this.taskSelect.getSelectedItem()).getKey().toString(),new Comparator<File>() {
			@Override
			public int compare(File o1, File o2) {
				int reVal=0;
				if(o1.lastModified()<o2.lastModified()){
					reVal=1;
				}else if(o1.lastModified()>o2.lastModified()){
					reVal=-1;
				}
				return reVal;
			}
		});
		String tempdt="";
		this.dateSelect.removeAllItems();
		this.dateSelect.addItem(SystemIdentification.getFullYear());
		for(int index=0;index<this.currentLogFile.length;index++){
			String datetime=logio.getLogDateTime(this.currentLogFile[index].getName()).split(" ")[0];
			if(!datetime.equals(tempdt)){
				this.dateSelect.addItem(datetime);
				tempdt=datetime;
			}
		}
    }
    
    private void changeLogList(){
    	this.panel2.removeAll();
    	for(int index=0;index<this.currentLogFile.length;index++){
    		String datetime=logio.getLogDateTime(this.currentLogFile[index].getName());
    		if(datetime.startsWith(this.dateSelect.getSelectedItem().toString())){
		    	ItemLabel loglab=new ItemLabel(datetime);
		    	loglab.setForeground(Color.GRAY);
		    	loglab.setAlignmentX(JLabel.CENTER_ALIGNMENT);
		    	loglab.setName(this.currentLogFile[index].getName());
		    	loglab.setActionCommand("loglab");
		    	loglab.addMouseListener(this.vpListener);
	    	   panel2.add(loglab);
	    	}
    	}
    	SwingUtilities.updateComponentTreeUI(panel2);
    }
	
	private void initView(){
		this.vpListener=new ViewPortListener();
		this.getContentPane().add(this.getTopPanel(),BorderLayout.PAGE_START);
		this.getContentPane().add(this.getLeftPanel(),BorderLayout.LINE_START);
		this.getContentPane().add(this.getContentPanel());
		this.logio=new LogIO();
	}
	
	private JPanel getTopPanel(){
		JPanel panel=new JPanel(new BorderLayout());
		JPanel panelA=new JPanel();
		JPanel panelB=new JPanel();
		JPanel panelC=new JPanel();
		
		JLabel taskNameLab=new JLabel(ResourceMessages.getString("LogViewPort.0"));
		JLabel dateLab=new JLabel(ResourceMessages.getString("LogViewPort.1"));
		JLabel sequenceLab=new JLabel(ResourceMessages.getString("LogViewPort.2"));
		this.sequenceField=new JTextField(10);
		this.sequenceField.setBorder(null);
		this.sequenceField.setEditable(false);
		this.sequenceField.setOpaque(false);
		this.taskSelect=new JComboBox();
		this.taskSelect.addItemListener(this.vpListener);
		this.dateSelect=new JComboBox();
		this.dateSelect.addItemListener(this.vpListener);
		
		this.refreshBut=new ItemLabel(ResourceMessages.getString("LogViewPort.3"));
		this.refreshBut.setForeground(Color.gray);
		this.refreshBut.addMouseListener(this.vpListener);
		this.refreshBut.setActionCommand("refreshBut");
		this.clearBut=new ItemLabel(ResourceMessages.getString("LogViewPort.4"));
		this.clearBut.setForeground(Color.gray);
		this.clearBut.addMouseListener(this.vpListener);
		this.clearBut.setActionCommand("clearBut");
		this.exitBut=new ItemLabel(ResourceMessages.getString("LogViewPort.5"));
		this.exitBut.setForeground(Color.gray);
		this.exitBut.addMouseListener(this.vpListener);
		this.exitBut.setActionCommand("exitBut");
		
		panelA.add(taskNameLab);
		panelA.add(this.taskSelect);
		panelA.add(dateLab);
		panelA.add(this.dateSelect);
		panelC.add(this.refreshBut);
		panelC.add(this.clearBut);
		panelC.add(this.exitBut);
		
		panelB.add(sequenceLab);
		panelB.add(this.sequenceField);
		panel.add(panelB,BorderLayout.LINE_START);
		panel.add(panelA);
		panel.add(panelC,BorderLayout.LINE_END);
		return panel;
	}
	
	private JPanel getLeftPanel(){
		JPanel panel0=new JPanel(new BorderLayout());
		JPanel panel1=new JPanel(new BorderLayout());
		JScrollPane jsp=null;
		
		JLabel titleIcon=new JLabel(new ImageIcon(this.getClass().getResource("images/logtitle.png")));
		panel1.add(titleIcon);
		
		jsp=new JScrollPane(panel2);
		panel0.add(panel1,BorderLayout.PAGE_START);
		panel0.add(jsp);
		return panel0;
	}
	
	private JScrollPane getContentPanel(){
		this.text=new JTextArea();
		this.text.setEditable(false);
		this.text.setFont(UIConst.FONT14);
		JScrollPane jsp=new JScrollPane(this.text);
		return jsp;
	}
	
	private void fillTaskNameSelect(Object[] kvs){
		DefaultComboBoxModel comboBox=new DefaultComboBoxModel(kvs);
		this.taskSelect.setModel(comboBox);
		this.taskSelect.setSelectedIndex(0);
		this.sequenceField.setText(((KeyValue)this.taskSelect.getSelectedItem()).getKey().toString());
	}
	
	private class ViewPortListener implements ItemListener,MouseListener{

		@Override
		public void itemStateChanged(ItemEvent e) {
				if(e.getSource()==taskSelect){
					if(e.getStateChange()==ItemEvent.SELECTED){
						 fillDateTimeSelect();
						 sequenceField.setText(((KeyValue)taskSelect.getSelectedItem()).getKey().toString());
					}
				}else if(e.getSource()==dateSelect){
					if(e.getStateChange()==ItemEvent.SELECTED)
						changeLogList();
				}
		}

		@Override
		public void mouseClicked(MouseEvent e) {
			ItemLabel lab=(ItemLabel)e.getComponent();
			if(lab.getActionCommand().equals("loglab")){
				StringBuilder logText=logio.readLog("logs/"+lab.getName());
				text.setText(logText.toString());
			}
			if(lab.getActionCommand().equals("refreshBut")){
				fillDateTimeSelect();
			}
			if(lab.getActionCommand().equals("clearBut")){
				int option=JOptionPane.showConfirmDialog(LogViewPort.this,ResourceMessages.getString("LogViewPort.6"),ResourceMessages.getString("LogViewPort.7"),JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE);
				 if(option==JOptionPane.YES_OPTION){
						logio.logClear();
						fillDateTimeSelect();
				 }
			}
			if(lab.getActionCommand().equals("exitBut")){
				isOpen=false;
				LogViewPort.this.dispose();
			}
		}

		@Override
		public void mousePressed(MouseEvent e) {
			ItemLabel lab=(ItemLabel)e.getComponent();
			lab.setForeground(Color.DARK_GRAY);
		}

		@Override
		public void mouseReleased(MouseEvent e) {
			ItemLabel lab=(ItemLabel)e.getComponent();
			lab.setForeground(Color.white);
		}

		@Override
		public void mouseEntered(MouseEvent e) {
			ItemLabel lab=(ItemLabel)e.getComponent();
			lab.setText(lab.getHtext());
			lab.setForeground(Color.WHITE);
			lab.setHorizontalAlignment(JLabel.CENTER);
			lab.setCursor(new Cursor(Cursor.HAND_CURSOR));
		}

		@Override
		public void mouseExited(MouseEvent e) {
			ItemLabel lab=(ItemLabel)e.getComponent();
			lab.setText(lab.getUtext());
			lab.setForeground(Color.GRAY);
		}
		
	}
	
}
